
/*
 * MODULE  NAME  :
 * PROGRAM NAME  : net.h
 * AUTHOR        : hotmocha(hotmocha@126.com)
 * CREATE  DATE  : 2015-10-21 08:49:53
 * PROGRAM DESC  :
 *
 * HISTORY       :
 *
 */
#ifndef _H_NET_H_
#define _H_NET_H_

#include <sys/epoll.h>
#include <arpa/inet.h>

#include "tkconstants.h"

#define EVENT_LOCAL_ERROR	1
#define EVENT_REMOTE_CLOSE	2
#define EVENT_READ		3
#define EVENT_WRITE		4

struct epoll_env;
struct custom_socket;

typedef int (*after_accept_entry)(struct epoll_env *env, struct custom_socket *s);
typedef int (*after_connect_entry)(struct epoll_env *env, struct custom_socket *s);
typedef int (*event_handler)(struct epoll_env *env, struct custom_socket *s, int event_type);

struct epoll_env {
	int epollfd;
	struct epoll_event *epoll_wait_events;	

	after_accept_entry after_accept;
	after_connect_entry after_connect;
};

struct net_addr {
	int port;
	char ipv4[IPV4LEN];
        struct sockaddr_in sockaddr;
};

struct custom_socket {
        int sockfd;
        struct net_addr addr;
	void* event;
	event_handler handler;
	int type;	/* listen or default */
	
	void *ptr;		/* point to own struct(tk_connect) */
};


void set_epoll_after_accept(struct epoll_env *env, after_accept_entry after_accept);
void set_epoll_after_connect(struct epoll_env *env, after_connect_entry after_connect);

int epoll_process_events(struct epoll_env* env, long timeout);
int epoll_add_event(struct epoll_env *env, void *event, int event_type);
int epoll_del_event(struct epoll_env *env, void *event, int event_type);
int epoll_add_listen_event(struct epoll_env *env, void *event);
int epoll_del_listen_event(struct epoll_env *env, void *event);
int epoll_add_read_event(struct epoll_env *env, void *event);
int epoll_add_write_event(struct epoll_env *env, void *event);
int epoll_del_read_event(struct epoll_env *env, void *event);
int epoll_del_write_event(struct epoll_env *env, void *event);

void set_event_data(void *pv, void *data);
void* get_event_data(void *pv);

struct custom_socket* get_custom_socket();
void destory_custom_socket(struct epoll_env *env, struct custom_socket *s);

struct epoll_env* create_epoll_env(after_accept_entry after_accept, after_connect_entry after_connect);
int destory_epoll_env(struct epoll_env *env);
void set_event_type(void *pv, int type);

#endif
